from fastapi import APIRouter

import requests
import json
from fastapi import FastAPI, File, UploadFile,Form
import os

router = APIRouter()

@router.get("/users/", tags=["users"])
async def read_users():
    return [{"username": "Foo"}, {"username": "Bar"}]


@router.get("/checklogin/")
async def check_login():

    res = requests.get("https://graph.facebook.com/debug_token?access_token=337974204227205%7Cdc75d0a1fb30f2952db3a6a39e3f0ac0&input_token=EAAEzYsBi3oUBAHQQ9w7jSW95FcZBflMnib1cHUpf9eMBnuSvNcvvg31oKtIGoZA9kYtpq3OLMNSgY01ErgZA21PDRqdz7APrdZAXFJ9k43TnJXH8ZADb9Cjr2JEevZCdPpyTOpsZBvxE7RC63JjxZBr60iNQjWlfwwGBqdS2knhXBebpWGezrkg5WLRuBaUi3IdZBIBozQp1KMdDUmNWyR365")

    res = json.loads(str(res.text))

    return res


@router.get("/getinfo/")
async def userinfo():

    res = requests.get(
        "https://graph.facebook.com/v8.0/1583917368454739?access_token=EAAEzYsBi3oUBAHQQ9w7jSW95FcZBflMnib1cHUpf9eMBnuSvNcvvg31oKtIGoZA9kYtpq3OLMNSgY01ErgZA21PDRqdz7APrdZAXFJ9k43TnJXH8ZADb9Cjr2JEevZCdPpyTOpsZBvxE7RC63JjxZBr60iNQjWlfwwGBqdS2knhXBebpWGezrkg5WLRuBaUi3IdZBIBozQp1KMdDUmNWyR365")

    res = json.loads(str(res.text))

    return res


@router.post("/uploadfile/")
async def uploadfile(file: UploadFile = File(...), chunkNumber: str = Form(...), identifier: str = Form(...)):

    task = identifier          # 获取文件唯一标识符
    chunk = chunkNumber        # 获取该分片在所有分片中的序号
    filename = '%s%s' % (task,chunk)           # 构成该分片唯一标识符
    contents = await file.read() #异步读取文件
    with open('./static/upload/%s' % filename, "wb") as f:
        f.write(contents)
    print(file.filename)
    return {"filename": file.filename}


@router.post("/mergefile/")
async def uploadfile(identifier: str = Form(...), filename: str = Form(...)):

    target_filename = filename  # 获取上传文件的文件名
    task = identifier              # 获取文件的唯一标识符
    chunk = 1                                       # 分片序号
    with open('./static/upload/%s' % target_filename, 'wb') as target_file:  # 创建新文件
        while True:
            try:
                filename = './static/upload/%s%d' % (task,chunk)
                # 按序打开每个分片
                source_file = open(filename, 'rb')
                # 读取分片内容写入新文件
                target_file.write(source_file.read())
                source_file.close()
            except IOError:
                break
            chunk += 1
            os.remove(filename)
    return {"code":200}







